/*
 * TimerActivity.cpp
 *
 *  Created on: 2022年5月8日
 *      Author: vicent-PC
 */
#define LOG_TAG "TimerActivity"

#include <HTTPClient.h>
#include <WiFi.h>
#include <stdio.h>
#include <time.h>

#include <string>

#include "Trace.h"
#include "./screen_hal/DisplayCanvas.h"
#include "oled/ESP8266_and_ESP32_OLED_driver_for_SSD1306_displays/src/OLEDDisplayUi.h"
#include "oled/ESP8266_and_ESP32_OLED_driver_for_SSD1306_displays/src/SSD1306Wire.h"
#include "oled/oled_drv_intf.h"

#include "SolarTrackActivity.h"
#include "TimerActivity.h"

#define LOG_TAG "TimerActivity"

TimerActivity * TimerActivity::m_pInstance = nullptr;

TimerActivity::TimerActivity() {
}

TimerActivity::~TimerActivity() {
    if (mCanvas != nullptr) {
        delete mCanvas;
        mCanvas = nullptr;
    }
    if (mView != nullptr) {
        delete mView;
        mView = nullptr;
    }
}

void getLocalTime2(char* timestr) {
    struct tm timeinfo;
    time_t rawtime;
    struct tm *info;

    time(&rawtime);

    info = localtime(&rawtime);
    // if (!getLocalTime(&timeinfo, 500)) {
    //     LOGW("Failed to obtain time, retry...");
    //     return;
    // }
    if (nullptr == info) {
        LOGW("Failed to obtain time, retry...");
        return;
    }
    snprintf(timestr, 16, "%d:%02d:%02d", info->tm_hour, info->tm_min,
             info->tm_sec);
}

void drawTimer() {
    char timestr[64];
    OLEDDisplay* tempPen = DisplayCanvas::getInstance()->getPen();
    getLocalTime2(timestr);
    tempPen->setFont(ArialMT_Plain_24);
    const int fontwidth = 24/2;
    tempPen->drawString((128 - strlen(timestr) * fontwidth) / 2, 0, timestr);
}

void TimerActivity::onDraw() {
    OLEDDisplay* tempPen = DisplayCanvas::getInstance()->getPen();
    tempPen->clear();
    drawTimer();
    tempPen->display();
}

void initCustomDisplay2() {
    OLEDDisplay* tempPen = DisplayCanvas::getInstance()->getPen();
    tempPen->clear();
    tempPen->drawRect(0, 0, 128, 64);
    tempPen->setTextAlignment(TEXT_ALIGN_LEFT);
    tempPen->setFont(ArialMT_Plain_10);
}

void TimerActivity::onCreate() {
    LOGI("%s E\n", __func__);
    int ret = 0;
    mView = new View();
    mCanvas = new Canvas();
    mView->add(mCanvas);
    setContentView(mView);

    // 1. initDisplay
    initCustomDisplay2();
}

void TimerActivity::onEvent() {
    LOGI("%s", __func__);
    SystemServer::getInstance()->startActivity((Activity*)SolarTrackActivity::getInstance());
}
